import { createLoadingComponent } from "./loading";
import type { IBinding, LoadingOptions } from "./types";

const resolveOptions = (target: HTMLElement | null = null, binding: IBinding): LoadingOptions => {
  if (!target) {
    target = document.body
  }
  return {
    parent: binding.modifiers?.body ? document.body : target,
    text: target?.getAttribute('vt-loading-text') ?? '',
    target,
    body: binding.modifiers?.body ? true : false
  }
}

const map = new Map()
export const vLoading = (el: HTMLElement, binding: IBinding) => {

  if (binding.value === binding.oldValue) {
    return
  }

  if (binding.value) {
    const resolve = resolveOptions(el, binding);

    const instance = createLoadingComponent(resolve)
    // TODO 创建的 loading dom 的 data-v-app 属性如何去除
    instance.parent?.appendChild(instance.$el)

    // 给父级 添加 定位
    instance.parent.style.position = "relative"

    instance.$el.classList.add("vt-loading__container")
    instance.$el.dataset.mode = instance.body ? "full" : 'part'

    if (!map.get(el)) {
      map.set(el, instance)
    }

  } else {
    const instance = map.get(el)
    if (instance) {
      destroySelf()
    }
  }

  function destroySelf() {
    const instance = map.get(el)
    instance.$el.remove()
    map.set(el, null)
  }

  return destroySelf
}
